//路由模块
const express = require('express')
// 创建路由对象
const router = express.Router()

const date = require("silly-datetime")
// 1. 导入 mysql 模块
const mysql = require('mysql')
// 2. 建立与 MySQL 数据库的连接关系
const db = mysql.createPool({
    multipleStatements: true,
    host: '*.*.*.*', // 数据库的 IP 地址
    port: '3306',
    user: 'server_test', // 登录数据库的账号
    password: 'lzf749882178', // 登录数据库的密码
    database: 'server_test' // 指定要操作哪个数据库
})
const  createToken = require('../util/authorization')
let timestamp = new Date().getTime()


// 用户端  创建积分记录
router.post('/createIntegral', (req, res) => {
    let time = date.format(new Date(), 'YYYY-MM-DD')
    console.log(req.body.userId,time)
    let selectIntegral = `select * from integral WHERE userId = ${req.body.userId} and createTime = '${time}'`

    db.query(selectIntegral, (error, results) => {
        let addIntegral = `INSERT INTO integral (userId, createTime, historyIntegral, geographyIntegral,botanyIntegral,animalIntegral, baseId) VALUES (${req.body.userId}, '${time}', 0, 0,0, 0,${req.body.baseId})`
        if(error) {
            db.query(addIntegral, (err, rez) => {
                if (err) {
                    res.send({
                        data: null,
                        msg: '查询错误a',
                        code: -1,
                        timestamp
                    })
                    return
                }
                res.send({
                    msg: '添加成功',
                    code: 200,
                    timestamp
                })
            })
        }
    })
})

// 添加积分
router.post('/addIntegral', (req, res) => {
    let time = date.format(new Date(), 'YYYY-MM-DD')
    console.log(time)
    let selectIntegral = `select * from integral WHERE userId = ${req.body.userId} and createTime = '${time}'`
    let type = {
        '1': 'historyIntegral',
        '2': 'geographyIntegral',
        '3': 'botanyIntegral',
        '4': 'animalIntegral'
    }
    let baseType = type[req.body.baseId]

    db.query(selectIntegral, (err, results) => {
        console.log(results, '1')
        // if (err) {
        //         let addIntegral = `INSERT INTO integral (userId, createTime, historyIntegral, geographyIntegral,botanyIntegral,animalIntegral, baseId) VALUES (${req.body.userId}, '${time}', 0, 0,0, 0,${req.body.baseId})`
        //         db.query(addIntegral, (error, rez) => {
        //             console.log(error)
        //             if (error) {
        //                 res.send({
        //                     data: null,
        //                     msg: '查询错误a',
        //                     code: -1,
        //                     timestamp
        //                 })
        //                 return
        //             }
        //             let updates = `update integral set ${baseType} = ${baseType} + 1 where userId = '${req.body.userId}' and createTime = '${time}'`
        //             db.query(updates, (error, rez) => {
        //                 console.log(baseType, '1')
        //                 if (error) {
        //                     res.send({
        //                         data: null,
        //                         msg: '查询错误b',
        //                         code: -1,
        //                         timestamp
        //                     })
        //                     return
        //                 }
        //                 res.send({
        //                     msg: '添加成功b',
        //                     code: 200,
        //                     timestamp
        //                 })
        //             })
        //         })
        //     return
        // }
        if (results.length) {
            let update = `update integral set ${baseType} = ${baseType} + 1 where userId = '${req.body.userId}' and createTime = '${time}'`
            db.query(update, (error, rez) => {
                console.log(baseType)
                if (error) {
                    res.send({
                        data: null,
                        msg: '查询错误b',
                        code: -1,
                        timestamp
                    })
                    return
                }
                res.send({
                    msg: '添加成功b',
                    code: 200,
                    timestamp
                })
            })
        } else {
            let addIntegrals = `INSERT INTO integral (userId, createTime, historyIntegral, geographyIntegral,botanyIntegral,animalIntegral, baseId) VALUES (${req.body.userId}, '${time}', 0, 0,0, 0,${req.body.baseId})`
            db.query(addIntegrals, (error, rez) => {
                console.log(error)
                if (error) {
                    res.send({
                        data: null,
                        msg: '查询错误a',
                        code: -1,
                        timestamp
                    })
                    return
                }
                let updates = `update integral set ${baseType} = ${baseType} + 1 where userId = '${req.body.userId}' and createTime = '${time}'`
                db.query(updates, (error, rez) => {
                    console.log(baseType, '1')
                    if (error) {
                        res.send({
                            data: null,
                            msg: '查询错误b',
                            code: -1,
                            timestamp
                        })
                        return
                    }
                    res.send({
                        msg: '添加成功b',
                        code: 200,
                        timestamp
                    })
                })
            })
        }
    })
})

//查询积分记录
router.post('/integral', (req, res) => {

    let time = date.format(new Date(), 'YYYY-MM-DD')
    console.log(time)
    let selectIntegral = `select * from integral where userId = '${req.body.userId}' and createTime = '${time}'`
    db.query(selectIntegral, (err, results) => {
        console.log(err)
        if (err) {
            res.send({
                data: null,
                msg: '查询错误',
                code: -1,
                timestamp
            })
            return
        }
        res.send({
            data: results,
            msg: 'ok',
            code: 200,
            timestamp
        })
    })
})

// 添加知识库
router.post('/addBase', (req, res) =>{
    // let selectOldUserId = `select userId from user order by id desc limit 1;`
    let addBaseId = `select id from book order by id desc limit 1`
    // let addBaseId = 'SELECT * FROM user'
    db.query(addBaseId, (err, results) => {
        // console.log(results)
        let id = 1
        if (results && results.length) {
            id = Number(results[0].id) + 1
        }

        let imgUrl =`'${req.body.imgUrl}'`
        let addBase = `INSERT INTO book (typeId, title, total, imgUrl) VALUES ('${req.body.typeId}', '${req.body.title}', ${req.body.total}, ${imgUrl})`
        db.query(addBase, (err, results) => {
            console.log(err, req.body)
            if (err) {
                res.send({
                    // data: {},
                    msg: 'err',
                    code: -1,
                    timestamp
                })
                return
            }
            res.send({
                // data:
                msg: 'ok',
                code: 200,
                timestamp
            })
        })
    })
})


// 查询所有的知识库
router.post('/baseList', (req, res) => {
    let selectSql = 'select * from book'
   db.query(selectSql, (err, results) => {
       res.send({
           data: results,
           msg: 'ok',
           code: 200,
           timestamp
       })
   })
})

// 更新知识库
router.post('/renewBase', (req, res) =>{
    let renewBase = `update book set typeId = '${req.body.typeId}', title = '${req.body.title}', total = ${req.body.total}, imgUrl= '${req.body.imgUrl}' where id = ${req.body.id}`
    db.query(renewBase, (err, results) => {
        res.send({
            data: results,
            msg: 'ok',
            code: 200,
            timestamp
        })
    })
})

// 添加题目
router.post('/addSubject', (req, res) => {
    let addBase = `INSERT INTO answer (baseId, subject, answerA, answerB, answerC, answerD, answer, analysis, subjectType) 
                       VALUES ('${req.body.baseId}','${req.body.subject}', '${req.body.answerA}', '${req.body.answerB}', '${req.body.answerC}','${req.body.answerD}', '${req.body.answer}', '${req.body.analysis}', ${req.body.subjectType})`
    db.query(addBase, (err, results) => {
        console.log(err, req.body)
        if (err) {
            res.send({
                // data: {},
                msg: 'err',
                code: -1,
                timestamp
            })
            return
        }
        res.send({
            // data:
            msg: 'ok',
            code: 200,
            timestamp
        })
    })
})

// 查所有的题  后台管理
router.post('/subjectList', (req, res) => {
    let selectSql = `select * from answer where baseId = '${req.body.id}' order by answerId desc`
    db.query(selectSql, (err, results) => {
        res.send({
            data: results,
            msg: 'ok',
            code: 200,
            timestamp
        })
    })
})

// 删除题目
router.post('/delSubject', (req, res) => {
    let delSubject = `DELETE FROM answer WHERE answerId = ${req.body.answerId}`
    db.query(delSubject, (err, rez) => {
        if(err) {
            res.send({
                msg: 'err',
                code: -1,
                timestamp
            })
            return
        }
        res.send({
            msg: 'ok',
            code: 200,
            timestamp
        })
    })
})


// 查知识库下所有的题  用户端
router.post('/foreEnd/subjectList', (req, res) => {
    let selectSql = `select * from answer where baseId = '${req.body.id}' order by answerId desc`
    db.query(selectSql, (err, results) => {
        let dataList = []
        results.forEach(item => {
            item.options = []
            if (item.subjectType == 1) {
                item.options.push({text: item.answerA, answerResult: 0})
                item.options.push({text: item.answerB, answerResult: 0})
                item.options.push({text: item.answerC, answerResult: 0})
                item.options.push({text: item.answerD, answerResult: 0})
            }
            delete item.answerA
            delete item.answerB
            delete item.answerC
            delete item.answerD
            dataList.push(item)
        })
        res.send({
            data: dataList,
            msg: 'ok',
            code: 200,
            timestamp
        })
    })
})

module.exports = router